package org.aeon.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author: MissingAeon
 * @date: 2024/1/26 10:33
 * @description:
 */
@Slf4j
public class RedisPoolUtils {
    private static JedisPool jedisPool;

    // 静态块，在类加载时初始化连接池
    static {
        initializeJedisPool();
    }

    private static void initializeJedisPool() {
        String resource = "redis.properties";
        try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
            final Properties properties = new Properties();
            properties.load(inputStream);

            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            jedisPoolConfig.setMaxTotal(10);  // 设置最大连接数
            // 其他配置可以根据需要添加

            // 创建连接池
            jedisPool = new JedisPool(jedisPoolConfig, properties.getProperty("host"), Integer.parseInt(properties.getProperty("port")));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     * 获取 Jedis 资源
     *
     * @return
     */
    public static Jedis getJedis() {
        if (jedisPool != null) {
            return jedisPool.getResource();
        }
        throw new RuntimeException("redis没有连接资源");
    }

    /**
     * 释放Jedis资源
     */
    public static void close(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
